package com.wmh.baseservice.robot.controller;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wmh.baseservice.common.job.quartz.SchedulerManager;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.web.UserUtil;
import com.wmh.baseservice.robot.entity.RobotJobTask;
import com.wmh.baseservice.robot.enums.RobotJobTaskStatus;
import com.wmh.baseservice.robot.job.TaskJobHandler;
import com.wmh.baseservice.robot.pojo.vo.robotjobtask.RobotJobTaskAddReqVO;
import com.wmh.baseservice.robot.pojo.vo.robotjobtask.RobotJobTaskPageReqVO;
import com.wmh.baseservice.robot.pojo.vo.robotjobtask.RobotJobTaskUpdateReqVO;
import com.wmh.baseservice.robot.service.RobotJobTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.stream.Collectors;

import static com.wmh.baseservice.common.utils.returnbody.ReturnBody.success;

/**
 * @author 谢骏
 * @date 2023/8/23 11:30
 **/
@Validated
@RestController
@RequestMapping("robot/jobTask")
@Api(tags = "自动化机器定时任务接口")
@Slf4j
public class RobotJobTaskController {

    @Resource
    private SchedulerManager schedulerManager;

    @Resource
    private RobotJobTaskService robotJobTaskService;


    @Resource
    private UserUtil userUtil;

    @ApiOperation("创建定时任务")
    @PostMapping("create")
    public String create(@Valid @RequestBody RobotJobTaskAddReqVO reqVO) throws SchedulerException {
        robotJobTaskService.create(reqVO);
        return success();
    }

    @ApiOperation("删除定时任务")
    @PostMapping("delete")
    public String delete(@NotNull(message = "未提交主键") Long id) throws SchedulerException {
        robotJobTaskService.delete(id);
        return success();
    }

    @ApiOperation("修改定时任务")
    @PostMapping("update")
    public String update(@Valid @RequestBody RobotJobTaskUpdateReqVO reqVO) throws SchedulerException {
        robotJobTaskService.update(reqVO);
        return success();
    }

    @ApiOperation("修改定时任务状态")
    @PostMapping("updateStatus")
    public String updateStatus(@NotNull(message = "未提交主键") Long id, @NotNull(message = "未提交状态") Integer status) throws SchedulerException {
        robotJobTaskService.updateStatus(id, status);
        return success();
    }

    @ApiOperation("分页")
    @GetMapping("page")
    public String page(@Valid RobotJobTaskPageReqVO reqVO) {
        boolean superAdmin = userUtil.isSuperAdmin();
        PageResult<RobotJobTask> result = new PageUtil<RobotJobTask>(reqVO).startPage((page, queryWrapper) -> {
            LambdaQueryWrapper<RobotJobTask> l = queryWrapper.lambda();
            queryWrapper.lambda()
                    .eq(StrUtil.isNotBlank(reqVO.getName()), RobotJobTask::getName, reqVO.getName())
                    .eq(reqVO.getStatus() != null, RobotJobTask::getStatus, reqVO.getStatus());
            if (superAdmin) {
                // 查看所有人
                if (reqVO.getLookMe() == null || BooleanUtil.isFalse(reqVO.getLookMe())) {
                    l.eq(reqVO.getAdId() != null, RobotJobTask::getAdId, reqVO.getAdId());
                } else {
                    // 只看自己
                    l.eq(RobotJobTask::getAdId, userUtil.getId());
                }
            } else {
                // 非超级管理员只看自己
                l.eq(RobotJobTask::getAdId, userUtil.getId());
            }
            robotJobTaskService.page(page, queryWrapper);
        });
        return success(result);
    }

    @ApiOperation("任务状态选项")
    @GetMapping("statusOptions")
    public String statusOptions() {
        return success(Arrays.stream(RobotJobTaskStatus.values()).map(item ->
                JSONObject.of("label", item.getLabel(), "value", item.getValue())
        ).collect(Collectors.toList()));
    }

    @ApiOperation("马上触发任务")
    @PostMapping("trigger")
    public String triggerJobTask(@NotNull(message = "未提交任务编号") Long jobId) throws SchedulerException {
        robotJobTaskService.triggerJobTask(jobId);
        return success();
    }

    @ApiOperation("公开测试接口")
    @GetMapping("public/test")
    public String test(@NotNull(message = "未提交主键") Long id, @NotBlank(message = "未提交 cron") String cron, @NotBlank(message = "未提交 param") String param) throws SchedulerException {
        schedulerManager.addJob(id, CharSequenceUtil.lowerFirst(TaskJobHandler.class.getSimpleName()), param, cron, 0, 0);
        return success();
    }
}
